<template>
  <je-panel class="menu-tree">
    <template #tbar>
      <div class="top">菜单地图</div>
    </template>

    <template #default>
      <div class="content">
        <div class="tree">
          <je-tree
            ref="jeTree"
            draggable
            :search="{ style: 'height:40px;' }"
            :tree-config="{
              trigger: 'cell-dblclick',
              rowField: 'id',
              parentField: 'parent',
            }"
            :loading="loading"
            size="mini"
            :data="treeData"
            @before-drop="beforedrop"
            @drop="sortTreeData"
            @current-change="handleSelect"
            @search-select="doSearchChange"
          >
            <!-- <template #nodeIcon="{ row }">
              <i :class="setIcon(row)" :style="setStyle(row)"></i>
            </template> -->
            <template #nodeDefault="{ row }">
              <div :class="row.isUse ? 'title' : 'title noUse'"
                >{{ row.title }}
                <je-tooltip
                  v-if="row.parent == 'ROOT' && !row.bean.MENU_LINK_TOPMENU_ID"
                  placement="top"
                  title="点击关联顶部菜单"
                >
                  <span style="margin-left: 5px; display: inline-block" @click="clickRow(row)"
                    ><i class="fal fa-unlink" style="color: #f9a646; font-size: 13px"
                  /></span>
                </je-tooltip>
              </div>
            </template>

            <template #action="options">
              <je-menu
                @click="
                  (args) => {
                    handleChangeMenuItem(args, options);
                  }
                "
              >
                <template v-if="options.row.nodeInfoType === 'MENU'">
                  <je-menu-item key="MENU" text="菜单">
                    <i style="margin: 0 6px 0 0" class="icon fal fa-folder"></i>
                    添加菜单</je-menu-item
                  >
                  <je-menu-item
                    v-for="item in arrMenu.filter((item) => item.code !== 'MENU')"
                    :key="item.code"
                    :text="item.text"
                  >
                    <i style="margin: 0 6px 0 0" class="icon" :class="item.icon"></i>
                    添加{{ item.text }}
                  </je-menu-item>

                  <je-divider
                    v-if="options.row.children.length === 0"
                    style="height: 2px; margin: 5px 0"
                  />
                  <je-menu-item v-if="options.row.children.length === 0" key="delete" text="删除">
                    <i style="margin: 0 6px 0 0" class="icon jeicon jeicon-times"></i>
                    删除
                  </je-menu-item>
                </template>

                <template v-if="options.row.nodeInfoType !== 'MENU'">
                  <je-menu-item
                    v-if="options.row.children && options.row.children.length === 0"
                    key="delete"
                    text="删除"
                  >
                    <i style="margin: 0 6px 0 0" class="icon jeicon jeicon-times"></i>
                    删除
                  </je-menu-item>
                </template>
              </je-menu>
            </template>
          </je-tree>
        </div>

        <!-- <div v-if="arrProduct.length > 0" class="select">
          <je-dropdown :trigger="['click']" placement="topCenter">
            <a class="ant-dropdown-link" @click.prevent>
              {{ selectProduct.PRODUCT_NAME }}
              <i class="fal fa-angle-down"></i>
            </a>
            <template #overlay>
              <je-menu style="min-width: 230px; max-width: 400px">
                <je-menu-item
                  v-for="item in arrProduct"
                  :key="item"
                  @click.stop="handleProductClick(item)"
                >
                  {{ item.PRODUCT_NAME }}
                </je-menu-item>
              </je-menu>
            </template>
          </je-dropdown>
        </div> -->
      </div>

      <AddMenu ref="addMenu"></AddMenu>
      <JeTopMenu ref="topMenu"></JeTopMenu>
    </template>
  </je-panel>
</template>

<script>
  import {
    ref,
    reactive,
    toRefs,
    defineComponent,
    watch,
    onMounted,
    nextTick,
    onBeforeMount,
  } from 'vue';
  import { Menu, Divider } from 'ant-design-vue';
  import { Modal, Panel, Tree } from '@jecloud/ui';

  import { useStore } from '@/store/app-store';

  import emitter from '@/eventBus';

  import AddMenu from '@/components/menu/add-menu.vue';

  import TopMenu from '@/components/menu/add-top-menu.vue';

  import { getMenuTree, doRemoveMenu, moveTree } from '@/api';

  import { getDDItemList, loadDDItemByCodes } from '@jecloud/utils';

  // 格式化树
  const formatTreeData = (data) => {
    data.forEach((item) => {
      if (item.children && item.children.length > 0) {
        formatTreeData(item.children);
      }

      // item.disabled = false;
      // 树形的启用和禁用
      item.isUse = item.disabled === '0';
      item.title = item.text;
    });

    return data;
  };

  export default defineComponent({
    name: 'MenuTree',
    components: {
      AddMenu,
      JeTree: Tree,
      JeMenu: Menu,
      JeMenuItem: Menu.Item,
      JeDivider: Divider,
      JePanel: Panel,
      JeTopMenu: TopMenu,
    },

    setup(props, { emit }) {
      const state = reactive({
        jeTree: ref(),
        store: useStore(),
        addMenu: ref(),
        topMenu: ref(),
        menuNode: {
          id: '',
          text: '',
          nodeInfoType: '',
          children: [],
        },
        loading: true,
        selectProduct: {},
        treeData: [],
        arrMenu: [],
        // arrProduct: [],
        activeId: '',
      });

      const methods = {
        clickRow(row) {
          state.topMenu.showCurrentTopModal(row);
        },
        handleSelect({ row }) {
          if (state.menuNode.id === row.id) {
            state.store.changeMenuNode({});
          } else {
            state.store.changeMenuNode(row);
          }
        },

        // 搜索框选中事件
        doSearchChange({ row }) {
          console.log('0000', row);
          methods.handleSelect({ row: row });
        },

        // 显示添加菜单弹出框
        handleChangeMenuItem(e, options) {
          const { tooltip } = options;
          tooltip.visible = false;

          if (e.item.text !== '删除') {
            state.store.changeMenuNode(options.row);
            state.addMenu.showCurrentModal({
              title: e.item.text,
              type: e.key,
            });
          } else {
            methods.handleDelete(options.row);
          }
        },

        handleDelete(item) {
          Modal.confirm(`确认删除：${item.text}?`, () => {
            methods.doDelete(item);
          });
        },

        // 删除菜单
        doDelete(item) {
          doRemoveMenu({
            ids: item.id,
            tableCode: 'JE_CORE_MENU',
            doTree: true,
          })
            .then((res) => {
              Modal.notice(res.message, 'success');

              // 刷新菜单树
              methods.getMenuTreeData('deleteMenuNode');
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        // 获取树
        getMenuTreeData(type, obj) {
          getMenuTree({
            node: '',
            rootId: '',
            j_query: '',
            tableCode: 'JE_CORE_MENU',
          })
            .then((res) => {
              const arr = formatTreeData(res.data.children);

              state.treeData = arr;

              state.loading = false;

              if (type === 'changeSelectProduct') {
                // 切换产品
                if (state.treeData.length > 0) {
                  state.store.changeMenuNode(state.treeData[0]);

                  state.jeTree.setSelectRow(state.treeData[0]);
                } else {
                  state.store.changeMenuNode({});
                }
              } else if (type === 'deleteMenuNode') {
                // 删除菜单
                state.store.changeMenuNode({});
              } else if (type === 'checkedMenu') {
                if (obj.isLoad) {
                  return false;
                }
                state.store.changeMenuNode({});
                setTimeout(() => {
                  const row = state.jeTree.getRowById(obj.id);
                  if (row) {
                    state.jeTree.setSelectRow(row);
                    methods.handleSelect({ row });
                  }
                }, 30);
              }
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        // 获取产品
        // getProductData() {
        //   getProDuct({
        //     tableCode: 'JE_PRODUCT_MANAGE',
        //     funcCode: 'JE_PLATFORM_PRODUCT_MANAGE',
        //     j_query: JSON.stringify({
        //       order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
        //       custom: [
        //         {
        //           code: 'PRODUCT_ENABLE_STATE',
        //           value: 1,
        //           type: '=',
        //           cn: 'and',
        //         },
        //       ],
        //     }),
        //   })
        //     .then((res) => {
        //       state.arrProduct = res.data.rows;
        //       state.selectProduct = state.arrProduct.length !== 0 ? state.arrProduct[0] : {};
        //       state.store.changeSelectProduct(state.selectProduct);

        //       methods.getMenuTreeData('changeSelectProduct');
        //     })
        //     .catch((error) => {
        //       Modal.alert(error.message, 'error');
        //     });
        // },

        // handleProductClick(item) {
        //   if (item.JE_PRODUCT_MANAGE_ID === state.selectProduct.JE_PRODUCT_MANAGE_ID) {
        //     return false;
        //   }

        //   state.selectProduct = item;
        //   state.store.changeSelectProduct(state.selectProduct);

        //   methods.getMenuTreeData('changeSelectProduct');
        // },

        beforedrop({ row, target, action }) {
          // 下面的类型不能添加任何节点
          if (
            ['MT', 'DIC', 'IDDT', 'CHART', 'REPORT', 'PORTAL', 'URL', 'IFRAME'].includes(
              target.nodeInfoType,
            ) &&
            action == 'insert'
          ) {
            return false;
          }
          if (
            ['MT', 'DIC', 'IDDT', 'CHART', 'REPORT', 'PORTAL', 'URL', 'IFRAME'].includes(
              row.nodeInfoType,
            ) &&
            target.parent == 'ROOT' &&
            action == 'sort'
          ) {
            return false;
          }
        },

        sortTreeData({ row, info, action }) {
          const params = {
            tableCode: 'JE_CORE_MENU',
            id: info.id,
            toId: '',
            place: '',
          };
          //如果拖拽在节点里面
          if (action == 'insert') {
            params.place = 'inside';
            params.toId = info.parentId;
          } else {
            //如果在节点的上面
            if (info.nextId != undefined) {
              params.place = 'above';
              params.toId = info.nextId;
            } else if (info.prevId != undefined) {
              params.place = 'below';
              params.toId = info.prevId;
            }
          }
          moveTree(params)
            .then((res) => {
              Modal.notice({ content: res.message, status: 'success' });
              emitter.emit('checkedMenu', row);
              emitter.emit('refreshForm', row);
            })
            .catch((e) => {
              Modal.alert(e.message, 'error');
            });
        },

        setIcon(obj) {
          let icon = '';
          if (obj.nodeInfoType === 'MENU') {
            icon = 'fas fa-folder';
          } else if (obj.nodeInfoType === 'MT') {
            icon = 'jeicon jeicon-function';
          } else if (obj.nodeInfoType === 'DIC') {
            icon = 'fal fa-book';
          } else if (obj.nodeInfoType === 'IDDT') {
            icon = 'fal fa-puzzle-piece';
          } else if (obj.nodeInfoType === 'CHART') {
            icon = 'fal fa-chart-pie';
          } else if (obj.nodeInfoType === 'REPORT') {
            icon = 'jeicon jeicon-report';
          } else if (obj.nodeInfoType === 'PORTAL') {
            icon = 'fal fa-home-alt';
          } else if (obj.nodeInfoType === 'URL') {
            icon = 'fal fa-link';
          } else if (obj.nodeInfoType === 'IFRAME') {
            icon = 'jeicon jeicon-iframe';
          }

          if (obj.iconCls && obj.iconCls !== 'null') {
            icon = obj.iconCls;
          }

          return obj.isUse ? icon : icon + ' noUse';
        },

        setStyle(obj) {
          if (obj.nodeInfoType === 'MENU') {
            return {
              color: '#ffba3d',
            };
          }
        },
      };

      watch(
        () => state.store.menuNode,
        (val, old) => {
          Object.keys(state.menuNode).forEach((item) => {
            state.menuNode[item] = val[item];
          });
        },
      );
      onBeforeMount(() => {
        loadDDItemByCodes(['JE_MENU_TYPE']).then(() => {
          const list = getDDItemList('JE_MENU_TYPE');
          list.unshift({
            code: 'MENU',
            text: '模块',
            icon: 'jeicon jeicon-title',
          });
          state.arrMenu = list;
        });
      });
      onMounted(() => {
        emitter.off('refreshMenu');
        emitter.on('refreshMenu', () => {
          methods.getMenuTreeData();
        });

        emitter.off('checkedMenu');
        emitter.on('checkedMenu', (row) => {
          methods.getMenuTreeData('checkedMenu', row);
        });

        // methods.getProductData();
        methods.getMenuTreeData();
      });

      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style lang="less">
  .menu-tree {
    .tree {
      .ant-input-affix-wrapper:hover {
        border: 1px solid #5c8dff !important;
        box-shadow: none !important;
      }
      .ant-input-affix-wrapper {
        border-color: #e6e6e6 !important;
        border-radius: 0;
      }
      .ant-input-affix-wrapper-focused {
        border: 1px solid #5c8dff !important;
        box-shadow: none !important;
      }
      .je-tree-search-wrapper {
        .ant-select {
          height: 100%;
          .ant-select-selector {
            height: 100%;
            .ant-select-selection-search-input {
              height: 100%;
              .ant-input-suffix {
                .anticon.ant-input-clear-icon {
                  top: 9px;
                }
              }
            }
          }
        }
      }
      .je-panel-item-region-default {
        border-left: 1px solid #e6e6e6;
        border-right: 1px solid #e6e6e6;
      }
    }
  }
</style>
<style lang="less" scoped>
  .menu-tree {
    ::-webkit-scrollbar {
      width: 0 !important;
    }
    .top {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 39px;
      border-top: 1px solid #e6e6e6;
      border-left: 1px solid #e6e6e6;
      border-right: 1px solid #e6e6e6;
      border-bottom: 1px solid transparent;
      background: #f7f9fc;
    }
    .content {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      border-bottom: 1px solid #e6e6e6;
      .tree {
        position: absolute;
        top: 0px;
        bottom: 0px;
        left: 0;
        right: 0;
        overflow: auto;
        .noUse {
          color: #00000040 !important;
          text-decoration: line-through;
        }
      }
      .select {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 40px;
        text-align: center;
        line-height: 40px;
        border: 1px solid #e6e6e6;
        font-size: 14px;
        background: #f7f9fc;
      }
    }
  }
</style>
